/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.opgea.crm.web.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.opgea.crm.common.SetupsAttributeQualifier;
import com.opgea.crm.common.SetupsModuleQualifier;
import com.opgea.crm.common.util.DateUtil;
import com.opgea.crm.domain.entities.Activity;
import com.opgea.crm.domain.entities.Employee;
import com.opgea.crm.domain.entities.Lead;
import com.opgea.crm.domain.entities.Opportunity;
import com.opgea.crm.domain.entities.SetupsValue;
import com.opgea.crm.domain.modal.JsonModelMap;
import com.opgea.crm.services.ActivityService;
import com.opgea.crm.services.CompanyService;
import com.opgea.crm.services.EmployeeService;
import com.opgea.crm.services.LeadService;
import com.opgea.crm.services.OpportunityService;
import com.opgea.crm.services.SetupService;
import com.opgea.crm.services.security.CrmUserServiceImpl;
import com.opgea.crm.web.form.ActivityForm;
import com.opgea.crm.web.form.DynamicActivityForm;
import com.opgea.crm.web.modal.LoggedUser;
import org.apache.log4j.Logger;



/**
 * 
 * @author User1
 */
@Controller
@RequestMapping(value = "activity")
public class ActivityController {
	Logger logger=Logger.getLogger(ActivityController.class);

	@Autowired
	SetupService setupService;
	@Autowired
	OpportunityService opportunityService;
	@Autowired
	ActivityService activityService;
	@Autowired
	LeadService leadService;
	@Autowired
	EmployeeService employeeService;
	@Autowired
	CompanyService companyService;
	@Autowired
	CrmUserServiceImpl userService;
	
	@RequestMapping(method = RequestMethod.GET)
	public String show(@RequestParam(required=false, value="tabIndex")
						String tabIndex,
						HttpServletRequest request) {
		
		return "activity";
	}

	@RequestMapping(method = RequestMethod.GET, value="showActivityDetailsInPopup")
	public @ResponseBody
	Map<String, Object> showLeadDetailsInPopup(@RequestParam("activityId")String activityId){
		Activity activity = activityService.find(new Long(activityId));
		logger.debug("Activity : >>> "+activity);
		return JsonModelMap.success().data(new DynamicActivityForm(activity));
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "save")
	public @ResponseBody
	Map<String, Object> save(
						@RequestBody ActivityForm form,
						@RequestParam(required=true, value="action")String action, HttpServletRequest request) {
		
			logger.debug("Activity >> save >> InsideMethod ");
			
			Activity activity = null;
			Opportunity opportunity = null;
			Lead lead = null;
			Employee assignedTo = null;
			
			if(action.equalsIgnoreCase("save")){
				System.out.println("Before Save method");
				activity = new Activity();
				opportunity = opportunityService.find(new Long(form.getOpportunityId()));
				lead = leadService.findLead(new Long(form.getLeadId()));
				assignedTo = employeeService.find(new Long(form.getAssignedToId()));
				System.out.println("After Save method");
				}
			if(action.equalsIgnoreCase("update")){
				System.out.println("Before update method");
				activity = activityService.find(new Long(form.getActivityId()));
				System.out.println("After update method");
				opportunity = opportunityService.find(new Long(form.getOpportunityId()));
				lead = activity.getLead();
				assignedTo = activity.getAssignTo();
				}
				
			System.out.println("ActivityType/Stage : "+form.getActivityTypeId()+" "+form.getStageId());
			activity.setActivityType(setupService.findById(form.getActivityTypeId()));
			activity.setAssignTo(assignedTo);
			activity.setSubject(form.getSubject());
			System.out.println("ActivityStage : "+form.getStageId());
			activity.setActivityStage(setupService.findById(form.getStageId()));
			activity.setActivityStatus(setupService.findById(form.getStatusId()));

			activity.setLead(lead);
			activity.setOpportunity(opportunity);
			
			activity.setNote(form.getNotes());
			activity.setPriority(setupService.findById(form.getPriorityId()));
			activity.setScheduledDate(DateUtil.stringToDate(form.getDueDate()));
			activity.setDuration(new Integer(form.getDuration()));
			activity.setReminderDate(DateUtil.stringToDate(form.getReminderDate()));

			if(action.equalsIgnoreCase("save")){
				logger.debug("Activity >> Save");
				activity.setCreatedBy(LoggedUser.getUser(request));
				activity.setCreatedAt(new Date());
				activityService.create(activity);
				}
			if(action.equalsIgnoreCase("update")){
				logger.debug("Activity >> Update");
				activityService.update(activity);
				}
		
		return JsonModelMap.success().data(activity.getId());
	}
	
	@RequestMapping(method = RequestMethod.GET, value="showDetails")
	public @ResponseBody 
	Map<String, Object> showDetails(
			@RequestParam(required=true, value="activityId")String activityId){
		Activity activity = activityService.find(new Long(activityId));
		return JsonModelMap.success().data(new ActivityForm(activity));
	}
	
	@RequestMapping(method = RequestMethod.GET, value="showRelatedToName")
	public @ResponseBody 
	Map<String, Object> showRelatedToName(
			@RequestParam(required = false, value="relatedToId")String relatedToId){
		ActivityForm form = new ActivityForm();
		Lead relatedTo = leadService.findLead(new Long(relatedToId));
		
		form.setRelatedCompany(relatedTo.getCompany().getName());
		form.setRelatedTo(relatedTo.getFirstName());
		form.setFirstName(relatedTo.getFirstName());
		form.setMiddleInitial(relatedTo.getMiddleInitial());
		form.setLastName(relatedTo.getLastName());
		/*form.setStage(relatedTo.geta);
		form.setStatus(StatusQualifier.Initial);
		form.setPriority(PriorityQualifier.High);
		form.setActivityType(ActionQualifier.Email);
		form.setOpportunity("SELECT");
		form.setAssignedTo("SELECT");
		form.setDuration("0");*/
		return JsonModelMap.success().data(form); 
	}

	@RequestMapping(method = RequestMethod.GET, value = "assignedTo")
	public @ResponseBody
	Map<String, Object> assignToList() {
		return JsonModelMap.success().data(employeeService.findAllEmployeeName());
	}

	@RequestMapping(method = RequestMethod.GET, value = "relatedTo")
	public @ResponseBody
	Map<String, Object> relatedToList() {
		return JsonModelMap.success().data(leadService.findAllLeadName());
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "relatedToByCompanyId")
	public @ResponseBody
	Map<String, Object> leadNameListByCompany(@RequestParam(required=true, value="companyId")
			long companyId){
		return JsonModelMap.success().data(leadService.findAllLeadNameByCompanyId(companyId));
	}	

    @RequestMapping(value ="/activityReqCombo" )
	public @ResponseBody
	Map<String ,Object> issueCombo(@RequestParam(value ="operation") String operation,HttpServletResponse response)
	{
		List<SetupsValue> result = null;
		if(operation.equalsIgnoreCase("actionTypes"))
			result  = setupService.listSetupValue(SetupsModuleQualifier.Activity.ordinal(),SetupsAttributeQualifier.Action.ordinal());
		if(operation.equalsIgnoreCase("stageTypes"))
			result = setupService.listSetupValue(SetupsModuleQualifier.Activity.ordinal(), SetupsAttributeQualifier.Stage.ordinal());
		if(operation.equalsIgnoreCase("statusTypes"))
			result = setupService.listSetupValue(SetupsModuleQualifier.Activity.ordinal(), SetupsAttributeQualifier.Status.ordinal());
		if(operation.equalsIgnoreCase("priorityTypes"))
			result = setupService.listSetupValue(SetupsModuleQualifier.Activity.ordinal(), SetupsAttributeQualifier.Priority.ordinal());
		return JsonModelMap.success().data(result);
	}


	@RequestMapping(method = RequestMethod.GET, value = "opportunitiesTitles")
	public @ResponseBody
	Map<String, Object> opportunityTitleList(@RequestParam(required=false, value="leadId")Long leadId) {
		return JsonModelMap.success().data(
				opportunityService.findAllOpportunitiesTitlesByLeadId(leadId));
				//opportunityService.findAllOpportunitiesTitles());
	}

	@RequestMapping(method = RequestMethod.GET, value = "companyNames")
	public @ResponseBody
	Map<String, Object> companyNameList() {
		return JsonModelMap.success().data(companyService.findAllCompanyName());
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "activitySearchCriteriaTypes")
	public @ResponseBody
	Map<String, Object> activitySearchCriteriaList() {
		return JsonModelMap.success().data(activityService.getActivitySearchCriteriaTypes());
	}
	
	@RequestMapping(method = RequestMethod.POST, value="deleteActivityDetail")
	public @ResponseBody
	Map<String, Object> opportunityId(@RequestParam("activityId")String activityId)
	{
		activityService.remove(new Long(activityId));
		return JsonModelMap.successWithMessage("success");
	}
	

}
